import {
    HistoryKeyword
} from "../../model/history-keyword.js"
const history = new HistoryKeyword()

import {
    HotTag
} from "../../model/hot-tag.js"

import {
    Search
} from "../../model/search.js"

import {
    showToast
} from "../../utils/ui.js"

Page({

    data: {
        historyArr: [],
        hotTags: [],
        searchRes: [],
        search: false,
        keyword: ''
    },
    onLoad: async function() {
        const historyArr = history.get()
        const hotTags = await HotTag.getHotSearchTags()
        this.setData({
            historyArr,
            hotTags
        })
    },

    async onSearch(e) {
        let keyword = e.detail.value || e.detail.name
        // 如果输入的是空值
        if (!keyword) {
            showToast('请输入关键字')
            return
        }
        history.save(keyword)
        this.setData({
            search: true,
            searchRes: [], //每次搜索清空上一次的数据
            historyArr: history.get()
        })

        const paging = Search.search(keyword)

        // 显示loading
        wx.lin.showLoading({
            color: "#157658",
            type: "flash",
            fullScreen: true
        })
        const data = await paging.getMoreData()
        wx.lin.hideLoading()
        this.bindItem(data, keyword)
    },

    bindItem(data, keyword) {
        if (data.accumulator.length) {
            this.setData({
                keyword,
                searchRes: data.accumulator
            })
            return
        }
        this.setData({
            keyword: ''
        })
        showToast("没有搜索到相关数据")
    },

    // 取消
    onCancel() {
        this.setData({
            search: false,
            keyword: ''
        })
    },

    // 历史搜索delect
    onDelete() {
        history.clear()
        this.setData({
            historyArr: []
        })
    }
})